# 使用提醒:
# 1. xbot包提供软件自动化、数据表格、Excel、日志、AI等功能
# 2. package包提供访问当前应用数据的功能，如获取元素、访问全局变量、获取资源文件等功能
# 3. 当此模块作为流程独立运行时执行main函数
# 4. 可视化流程中可以通过"调用模块"的指令使用此模块

import sys
import os
import datetime
import pandas as pd
import time
script_dir =os.path.dirname(os.path.abspath(__file__))
sys.path.append(script_dir)
sys.path.append(r"D:\my_work\ac_lingxing_api\ac_lingxing_api")
# sys.path.append(os.path.join(os.path.split(os.path.split(sys.path[0])[0])[0], "database"))
# sys.path.append(os.path.join(os.path.split(os.path.split(sys.path[0])[0])[0], "operation"))
from amz_ziniao import AmzLogin
from database.mysql_utils import MysqlConnect_ad_api, MysqlConnect_rpa
from selenium import webdriver
from selenium.common import NoSuchElementException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pywinauto
from pywinauto.keyboard import send_keys

class upload_file:

    def __init__(self):
        self.engine = MysqlConnect_rpa.mysql_connect()
        mysql_con = MysqlConnect_rpa()
        self.conn = mysql_con.connection
        self.cur = self.conn.cursor()


    def get_need_upload(self):
        query = "select * from new_sku_insert where is_upload = 0"
        query_df = pd.read_sql(query, con=self.engine)
        return query_df
    def choose_file(self, save_path):
        # file_path, file_name = os.path.split(save_path)
        # 使用pywinauto来选择文件
        app = pywinauto.Desktop()
        for i in range(10):
            # 选择文件上传的窗口
            try:
                dlg = app["打开"]
                # 选择文件地址输入框，点击激活
                # dlg["Toolbar3"].click()
                # time.sleep(0.5)
                # # 键盘输入上传文件的路径
                # file_path = file_path.replace(" ", "{SPACE}")
                # send_keys(file_path)
                # time.sleep(0.5)
                # # 键盘输入回车，打开该路径
                # send_keys("{VK_RETURN}")
                time.sleep(0.5)
                # 选中文件名输入框，输入文件名
                dlg["文件名(&N):Edit"].type_keys(save_path.replace("/","\\").replace(" ", "{SPACE}"))
                time.sleep(0.5)
                # 点击打开
                send_keys("{VK_RETURN}")
                time.sleep(0.5)
            except Exception as e:
                print(e)
            if dlg.exists():
                continue
            else:
                break

    def click_ele(self, driver, ele):
        WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.XPATH, ele)))
        driver.find_element(By.XPATH, ele).click()

    def upload(self, amz, driver, save_path, country):
        if country == "美国":
            url = "https://advertising.amazon.com/bulksheet/HomePage"
        elif country == "英国":
            url = "https://advertising.amazon.co.uk/bulksheet/HomePage"
        elif country == "德国":
            url = "https://advertising.amazon.de/bulksheet/HomePage"
        elif country == "意大利":
            url = "https://advertising.amazon.it/bulksheet/HomePage"

        res = amz.open_launcher_page(driver, url)
        if res:
            print("成功打开广告页面:", save_path)
        else:
            print("打开页面失败:", save_path)
            return None
        self.click_ele(driver, "//div[@id='aBrowse-div']/button" )
        time.sleep(3)
        self.choose_file(save_path)
        time.sleep(3)
        self.click_ele(driver, "//i[@data-testid='storm-ui-icon-upload']" )
        return True








    def update_statue(self, save_path):
        query = f"""UPDATE new_sku_insert set is_upload = 1, update_time = '{datetime.datetime.now()}' where save_path = '{save_path}' """
        
        self.conn.ping(reconnect=True)
        self.cur.execute(query)
        self.conn.commit()
        
    
    def main(self, amz):
        query_df = self.get_need_upload()
        for i, df in query_df.iterrows():
            browserOauth = df['browserOauth']
            save_path = df['save_path']
            seller_id = df['seller_id']
            account_name = df['account_name']
            country = df['country']
            driver = amz.amz_designate_store_login(browserOauth, account_name, country)
            res = self.upload(amz, driver, save_path, country)
            if res:
                self.update_statue(save_path)
            amz.close_store(browserOauth)
            print(f"关闭店铺{account_name}")


def main():
    amz = AmzLogin()
    up_file = upload_file()
    up_file.main(amz)

if __name__ == "__main__":
    main()

